<template>
    <div class="scan-page">
        <!-- 入库单信息 -->
        <div class="page-card">
            <div class="page-title">
                <div class="title-content">
                    <span>入库单信息</span>
                    <!-- <image src="../../static/icons/print.png" class="print-icon" /> -->
                </div>
            </div>

            <!-- 信息项 -->
            <div class="info-list">
                <div class="list-item">
                    <div class="item-title">入库单号</div>
                    <div class="item-content">{{ detailInfo.receiptOrderNum }}</div>
                </div>

                <div class="list-item">
                    <div class="item-title">产品类型</div>
                    <div class="item-content">{{ detailInfo.productType }}</div>
                </div>

                <div class="list-item">
                    <div class="item-title">产品代码</div>
                    <div class="item-content">015{{ detailInfo.productCode }}</div>
                </div>

                <div class="list-item">
                    <div class="item-title">入库箱数</div>
                    <div class="item-content">{{ detailInfo.boxesNum }}</div>
                </div>

                <div class="list-item">
                    <div class="item-title">轮胎数量</div>
                    <div class="item-content">{{ detailInfo.tiresNum }}</div>
                </div>

                <div class="list-item">
                    <div class="item-title">入库员工</div>
                    <div class="item-content">{{ detailInfo.employeeNum }}</div>
                </div>
            </div>
        </div>

        <uni-collapse class="my-3">
            <!-- 自己的可修改 -->
            <uni-collapse-item title-border="none" :border="false" :open="true">
                <template v-slot:title>
                    <div class="page-title collapse-title">
                        <div class="scan-title">
                            <span>投喂</span>
                            <span class="font-medium ml-2">{{ myScanList.createUser }}</span>
                        </div>
                    </div>
                </template>
                <div class="collapse-content">
                    <div class="number-box">
                        <div class="number-item">
                            <div class="text-warning item-value">{{ getTiresNum(myScanList.scanList) }}</div>
                            <div class="item-text">已扫胎数</div>
                        </div>

                        <div class="number-item">
                            <div class="text-success item-value">{{ mySuccess }}</div>
                            <div class="item-text">正确数量</div>
                        </div>

                        <div class="number-item">
                            <div class="text-danger item-value">{{ myError }}</div>
                            <div class="item-text">错误数量</div>
                        </div>
                    </div>

                    <div class="scan-list">
                        <uni-swipe-action>
                            <div class="page-card">
                                <div class="scan-content">
                                    <uni-icons type="info-filled" color="#FF9F08" size="28" />
                                    <div class="center-content">请扫包装箱标签</div>
                                    <image
                                        class="right-arrow"
                                        src="../../static/icons/right.png"
                                        mode="widthFix"
                                    />
                                </div>
                            </div>

                            <div
                                class="page-card"
                                v-for="(scan, index) in myScanList.scanList"
                                :key="index"
                                :id="scan.itemId"
                            >
                                <uni-swipe-action-item
                                    :right-options="[
                                        {
                                            text: '删除',
                                            style: {
                                                backgroundColor: '#D81E06',
                                                fontSize: '14px',
                                            },
                                        },
                                    ]"
                                    @click="removeScan(index)"
                                >
                                    <div class="scan-content">
                                        <uni-icons
                                            :type="scan.type === 'error' ? 'clear' : 'checkbox-filled'"
                                            :color="scan.type === 'error' ? '#D81E06' : '#52C41B'"
                                            size="28"
                                        />
                                        <div
                                            class="center-content"
                                            :class="scan.type === 'error' ? 'text-danger' : ''"
                                        >
                                            {{ formatScan(scan.code) }}
                                        </div>
                                    </div>
                                </uni-swipe-action-item>
                            </div>
                        </uni-swipe-action>
                    </div>
                </div>
            </uni-collapse-item>

            <!-- 其他人的只展示 -->
            <uni-collapse-item
                title-border="none"
                :border="false"
                v-for="(record, v) in otherScanList"
                :key="v"
            >
                <template v-slot:title>
                    <div class="page-title collapse-title">
                        <div class="scan-title">
                            <span>投喂</span>
                            <span class="font-medium ml-2">{{ record.createUser }}</span>
                        </div>
                    </div>
                </template>
                <div class="collapse-content">
                    <div class="number-box">
                        <div class="number-item">
                            <div class="text-warning item-value">{{ getTiresNum(record.scanList) }}</div>
                            <div class="item-text">已扫胎数</div>
                        </div>

                        <div class="number-item">
                            <div class="text-success item-value">{{ record.scanList?.length || 0 }}</div>
                            <div class="item-text">正确数量</div>
                        </div>

                        <div class="number-item">
                            <div class="text-danger item-value">0</div>
                            <div class="item-text">错误数量</div>
                        </div>
                    </div>

                    <div class="scan-list">
                        <div class="page-card" v-for="(scan, index) in record.scanList" :key="index">
                            <div class="scan-content">
                                <uni-icons
                                    :type="scan.type === 'error' ? 'clear' : 'checkbox-filled'"
                                    :color="scan.type === 'error' ? '#D81E06' : '#52C41B'"
                                    size="28"
                                />
                                <div
                                    class="center-content"
                                    :class="scan.type === 'error' ? 'text-danger' : ''"
                                >
                                    {{ formatScan(scan.code) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </uni-collapse-item>
        </uni-collapse>

        <uni-collapse class="my-3" v-if="validateList && validateList.length">
            <uni-collapse-item
                title-border="none"
                :border="false"
                v-for="(record, v) in validateList"
                :key="v"
            >
                <template v-slot:title>
                    <div class="page-title collapse-title">
                        <div class="scan-title">
                            <span>扫码校验</span>
                            <span class="font-medium ml-2">{{ record.createUser }}</span>
                        </div>
                    </div>
                </template>
                <div class="collapse-content">
                    <div class="number-box">
                        <div class="number-item">
                            <div class="text-warning item-value">{{ getTiresNum(record.scanList) }}</div>
                            <div class="item-text">已扫胎数</div>
                        </div>

                        <div class="number-item">
                            <div class="text-success item-value">{{ record.scanList?.length || 0 }}</div>
                            <div class="item-text">正确数量</div>
                        </div>

                        <div class="number-item">
                            <div class="text-danger item-value">0</div>
                            <div class="item-text">错误数量</div>
                        </div>
                    </div>

                    <div class="scan-list">
                        <div class="page-card" v-for="(scan, index) in record.scanList" :key="index">
                            <div class="scan-content">
                                <uni-icons
                                    :type="scan.type === 'error' ? 'clear' : 'checkbox-filled'"
                                    :color="scan.type === 'error' ? '#D81E06' : '#52C41B'"
                                    size="28"
                                />
                                <div
                                    class="center-content"
                                    :class="scan.type === 'error' ? 'text-danger' : ''"
                                >
                                    {{ formatScan(scan.code) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </uni-collapse-item>
        </uni-collapse>

        <!-- 下方固定的提交栏 -->
        <div class="btn-box">
            <div class="cancel-box" @click="goBack()">取 消</div>
            <div
                class="save-box"
                @click="saveData"
                v-show="hasRight(['0901-SCANSAVE']) && detailInfo.productType === 'WI'"
            >
                保 存
            </div>
            <div
                class="submit-box"
                @click="submitData"
                v-show="hasRight(['0901-SCAN']) && detailInfo.productType === 'WI'"
            >
                结 束
            </div>
        </div>

        <uni-popup ref="popup" type="dialog">
            <uni-popup-dialog
                title="提醒"
                type="warn"
                content="是否确认删除扫码结果?"
                @confirm="popConfirm"
            ></uni-popup-dialog>
        </uni-popup>

        <scanUtil />
    </div>
</template>

<script lang="ts" setup>
    import { detail, scan, submit } from '@/api/pda'
    import { userStore } from '@/store/modules/user'
    import { goBack, formatScan, hasRight, goTo, getTiresNum } from '@/utils/publicFuc'
    import scanUtil from '../component/scanUtil.vue'

    const detailInfo = ref<AnyObject>({})
    const myScanList = ref<AnyObject>({})
    const otherScanList = ref<AnyObject[]>([])

    const pageId = ref('')
    const validateList = ref<AnyObject[]>([])
    const loadData = (id: string) => {
        detail(id).then((res: any) => {
            detailInfo.value = res.data
            const { scanRecordList, id } = res.data
            pageId.value = id
            const recordList = [] as AnyObject[]
            // 扫码校验信息
            scanRecordList
                .filter((el: { scanType: string }) => el.scanType === '0')
                .forEach((record: AnyObject) => {
                    const key = record.createUser
                    const index = validateList.value.findIndex(item => item.createUser === key)
                    // 没有时创建元素
                    if (index < 0) {
                        validateList.value.push({
                            createUser: record.createUser,
                            scanList: [{ code: record.barCode, type: 'success' }],
                        })
                    } else {
                        validateList.value[index].scanList.push({ code: record.barCode, type: 'success' })
                    }
                })

            // 投喂信息
            scanRecordList
                .filter((el: { scanType: string }) => el.scanType === '1')
                .forEach((record: AnyObject) => {
                    const key = record.createUser
                    const index = recordList.findIndex(item => item.createUser === key)
                    // 没有时创建元素
                    if (index < 0) {
                        recordList.push({
                            createUser: record.createUser,
                            scanList: [{ code: record.barCode, type: 'success' }],
                        })
                    } else {
                        recordList[index].scanList.push({ code: record.barCode, type: 'success' })
                    }
                })
            const { userInfo } = userStore()
            const { userName } = userInfo
            // 我的
            myScanList.value = recordList.find(item => item.createUser === userName) || {
                createUser: userName,
                scanList: [],
            }
            // 其他人的
            otherScanList.value = recordList.filter(item => item.createUser !== userName)

            if (detailInfo.value.productType === 'FB')
                uni.showToast({ title: '折叠胎无法投喂', icon: 'error', duration: 3000 })
        })
    }

    const pageCode = ref('')

    onLoad((option: any) => {
        const { id } = option
        pageCode.value = id
        loadData(pageCode.value)
    })

    onShow(() => {
        uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器
        uni.$on('scancodedate', data => doScan(data))
    })
    onHide(() => {
        // 离开页面前清除监听器
        uni.$off('scancodedate')
    })

    const mySuccess = ref(0)
    const myError = ref(0)
    watch(
        myScanList,
        (val: any) => {
            const { scanList } = val
            if (!scanList || !scanList.length) {
                mySuccess.value = 0
                myError.value = 0
            } else {
                mySuccess.value = scanList.filter((item: any) => item.type === 'success')?.length || 0
                myError.value = scanList.filter((item: any) => item.type === 'error')?.length || 0
            }
        },
        { deep: true }
    )

    const doScan = (data: any) => {
        const { code } = data
        let hasScan = false
        // 自己
        const myIndex = myScanList.value.scanList.findIndex((item: { code: string }) => item.code === code)
        if (myIndex !== -1) hasScan = true
        else {
            // 其他人
            for (const record of otherScanList.value) {
                const otherIndex = record.scanList.findIndex((item: { code: string }) => item.code === code)
                if (otherIndex !== -1) {
                    hasScan = true
                    break
                }
            }
        }

        if (hasScan) return uni.showToast({ title: '本条码已扫描过', icon: 'error', duration: 3000 })

        // 一些校验
        let type = 'success'
        // 扫码识别错误的情况
        if (code.length < 30) {
            uni.showToast({ title: '参数错误,请检查并删除错误记录', icon: 'none', duration: 3000 })
            type = 'error'
        } else {
            const scanResultCode = code.substring(3, 7)
            // 扫描的产品代码
            if (scanResultCode !== detailInfo.value.productCode) {
                uni.showToast({ title: '参数错误,请检查并删除错误记录', icon: 'none', duration: 3000 })
                type = 'error'
            }
        }

        const itemId = 't_' + new Date().valueOf()
        myScanList.value.scanList.push({
            code,
            type,
            itemId,
        })
        setTimeout(() => {
            const idText = '#' + itemId
            uni.pageScrollTo({
                selector: idText,
                duration: 100,
            })
        }, 500)
    }

    // 删除
    const popup = ref<any>(null)
    const spliceIndex = ref(0)
    const removeScan = (index: number) => {
        popup.value.open()
        spliceIndex.value = index
    }

    const popConfirm = () => {
        myScanList.value.scanList.splice(spliceIndex.value, 1)
    }

    // 保存
    const saveData = () => {
        if (!myScanList.value.scanList.length)
            return uni.showToast({ title: '请进行扫码', icon: 'error', duration: 3000 })
        const params = {
            barCodeList: myScanList.value.scanList.map((item: any) => item.code),
            id: pageId.value,
            createUser: myScanList.value.createUser,
            // 投喂扫码
            scanType: '1',
        }
        scan(params).then(() => {
            uni.showToast({ title: '信息保存成功', icon: 'success', duration: 3000 })
        })
    }

    // 提交(传所有)
    //     const submitData = () => {
    //         const allRecord = [...otherScanList.value, myScanList.value]
    //         const allList = []
    //         for (let record of allRecord) {
    //             for (let item of record.scanList) {
    //                 allList.push(item.code)
    //             }
    //         }
    //         const params = {
    //             barCodeList: allList,
    //             id: pageId.value,
    //             createUser: myScanList.value.createUser,
    //         }
    //         submit(params).then(() => {
    //             uni.showToast({ title: '入库单保存成功', icon: 'success' })
    //         })
    // }

    // 提交(只传自己)

    const submitData = () => {
        const allRecord = [...otherScanList.value, myScanList.value]
        const allList = []
        for (let record of allRecord) {
            for (let item of record.scanList) {
                allList.push(item.code)
            }
        }
        // 只要有扫码就能上传
        if (!allList.length) return uni.showToast({ title: '请进行扫码', icon: 'error', duration: 3000 })
        const errorItem = myScanList.value.scanList.findIndex(
            (item: { type: string }) => item.type === 'error'
        )

        // 有错误就不上传
        if (errorItem !== -1) return uni.showToast({ title: '产品信息有错误', icon: 'error', duration: 3000 })
        const params = {
            barCodeList: myScanList.value.scanList.map((item: any) => item.code),
            id: pageId.value,
            createUser: myScanList.value.createUser,
            scanType: '1',
        }
        submit(params).then(() => {
            uni.showToast({ title: '投喂已结束', icon: 'success', duration: 3000 })
            setTimeout(() => {
                goTo('/pages/detail/index?id=' + pageCode.value)
            }, 3000)
        })
    }
</script>

<style lang="scss" scoped>
    .scan-page {
        @apply min-h-screen bg-pagebg p-4 pb-20 box-border;
        .title-content {
            @apply flex justify-between items-center flex-1;
            .print-icon {
                @apply w-4 h-4;
            }
        }
        .info-list {
            .list-item {
                @apply flex py-4 justify-between;
                &:not(:last-of-type) {
                    @apply border-b border-line border-solid border-0;
                }

                .item-content {
                    @apply flex-1 text-right text-grayText ml-4 break-all;
                }
            }
        }

        :deep(.uni-collapse) {
            @apply bg-transparent;
            .uni-collapse-item {
                @apply my-3 bg-white rounded-lg overflow-hidden  #{!important};
            }

            .collapse-title {
                @apply p-4 pb-0;
            }
            .collapse-content {
                @apply bg-pagebg;
            }
        }
        .number-box {
            @apply flex justify-evenly pb-4 bg-white rounded-b-lg;
            .number-item {
                @apply flex flex-col items-center;
                .item-value {
                    @apply font-bold text-xl mb-2;
                }
            }
        }
        .scan-list {
            .page-card {
                @apply my-3 px-2;
                .scan-content {
                    @apply flex justify-between items-center;
                }
                .center-content {
                    @apply flex-1 mx-4 break-all;
                }
                .right-arrow {
                    @apply w-1;
                }
            }
        }

        .btn-box {
            box-shadow: 0 -1px 0 1px #ededed;
            @apply fixed left-0 bottom-0 flex justify-between items-center p-4 bg-white
                w-screen box-border;
            .cancel-box {
                @apply py-3 rounded text-grayText border border-solid border-grayText flex-1 text-center;
            }
            .save-box {
                @apply py-3 rounded text-primary border border-solid border-primary ml-4 flex-1 text-center;
            }
            .submit-box {
                @apply py-3 rounded text-white bg-primary flex-1 text-center ml-4;
            }
        }
    }
</style>
